#include "MiddleRegion.h"
#include "SentinelBridgeSpace.h"
#include "PortalOfPowerSpace.h"
#include "InstructionFactory.h"
#include "Space.h"

namespace talisman_map
{

MiddleRegion::MiddleRegion()
{

}

void MiddleRegion::generateRegion(SentinelBridgeSpace * iSentinelBridgeCell, PortalOfPowerSpace * iPortalOfPowerSpace, vector<std::string> &spaces)
{
	iSentinelBridgeCell->setPicture("Images\\bridge-middleSide2.gif");

	Space * wStartSpace = new Space();
	wStartSpace->setDescription("Castle - Rest well.");
	setStartSpace(wStartSpace);

	Space * wNextSpace;
	Space * wPrevSpaceOfNextSpace = wStartSpace;

	for (unsigned i = 0; i < spaces.size(); ++i)
	{
		wNextSpace = new Space();
		if(i==2 && (wPrevSpaceOfNextSpace!=iSentinelBridgeCell)){
			wNextSpace = iSentinelBridgeCell;
			wNextSpace->setDescription(iSentinelBridgeCell->getDescription());
			wNextSpace->setPrevSpace(wPrevSpaceOfNextSpace);
			wPrevSpaceOfNextSpace->setNextSpace(wNextSpace);
			i--;
		}		
		else if( i==10 &&(wPrevSpaceOfNextSpace!=iPortalOfPowerSpace)){
			wNextSpace = iPortalOfPowerSpace;
			wNextSpace->setPrevSpace(wPrevSpaceOfNextSpace);
			wPrevSpaceOfNextSpace->setNextSpace(wNextSpace);
			wNextSpace->setDescription(iPortalOfPowerSpace->getDescription());
			i--;
		}

		else{
			
			if (spaces[i].find('/') != std::string::npos)
			{
				std::string wDescr = spaces[i].substr(0, spaces[i].find('/'));
				std::string wInstructionName = spaces[i].substr(wDescr.length()+1);
				Instruction * wInstruction = InstructionFactory::instructionFromString(wInstructionName);
				wNextSpace->setInstruction(wInstruction);
				wNextSpace->setDescription(wDescr);
			}
			else
				wNextSpace->setDescription(spaces[i]);

			wNextSpace->setPrevSpace(wPrevSpaceOfNextSpace);
			wPrevSpaceOfNextSpace->setNextSpace(wNextSpace);
		}
		wPrevSpaceOfNextSpace = wNextSpace;
	}

	wNextSpace->setNextSpace(wStartSpace);
	wStartSpace->setPrevSpace(wNextSpace); // Now totally circular

	getStartSpace()->setColor(Qt::yellow);
	getStartSpace()->setPicture("Images\\space3-middle.gif");
	for (Space * sp = getNextSpace(getStartSpace()); sp != getStartSpace(); sp = getNextSpace(sp))
	{
		sp->setColor(Qt::yellow);

		PortalOfPowerSpace *pop = dynamic_cast<PortalOfPowerSpace *>(sp);
		SentinelBridgeSpace *sb = dynamic_cast<SentinelBridgeSpace *>(sp);
		if (0 == pop && 0 == sb)
			sp->setPicture("Images\\space3-middle.gif");
	}
}
}

